package com.anysoft.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * URL构造器
 *
 * @since  1.6.13.26 [20201114 duanyy] <br>
 */
public class UrlBuilder {

    /**
     * 编码
     */
    public static final String ENCODING_UTF8 = "utf-8";

    /**
     * logger of slf4j
     */
    public static final Logger LOG = LoggerFactory.getLogger(UrlBuilder.class);

    /**
     * 基础url
     */
    protected String base;

    /**
     * 参数
     */
    protected List<Pair<String,String>> params = new ArrayList<Pair<String,String>>();

    public UrlBuilder(){

    }

    public UrlBuilder(String base){
        this.base = base;
    }

    public UrlBuilder setBase(String base){
        this.base = base;
        return this;
    }


    public UrlBuilder addParameters(String name,String value){
        params.add(new Pair.Default<String,String>(name,value));
        return this;
    }

    public String build(){
        return build(ENCODING_UTF8,false);
    }

    public String build(String encoding){
        return build(encoding,false);
    }

    public String build(boolean toHash){
        return build(ENCODING_UTF8,toHash);
    }

    public String build(String encoding,boolean toHash){
        String segmentQuery;
        String segmentHash;

        int index = base.indexOf('#');
        if (index < 0){
            segmentQuery = base;
            segmentHash = "";
        }else{
            segmentQuery = base.substring(0,index);
            segmentHash = base.substring(index + 1);
        }

        StringBuffer buffer = new StringBuffer(base.length());

        if (toHash){
            buffer.append(segmentQuery);
            buffer.append("#");
        }

        String src = toHash ? segmentHash : segmentQuery;

        int pos = src.indexOf('?');
        if (pos < 0){
            buffer.append(src);
            buffer.append("?");
        }else{
            buffer.append(src.substring(0,pos));
            buffer.append("?");
        }

        boolean first = true;
        for (Pair<String,String> p:this.params){
            String key = p.key();
            String value = p.value();
            if (StringUtils.isNotEmpty(value)){
                try {
                    if (!first){
                        buffer.append("&");
                    }
                    String encodeValue = URLEncoder.encode(value, encoding);
                    buffer.append(key).append("=").append(encodeValue);
                    first = false;
                } catch (UnsupportedEncodingException e) {
                    LOG.error(String.format("Encoding %s is not supported", encoding));
                }
            }
        }

        if (pos >= 0) {
            String left = src.substring(pos + 1);
            if (StringUtils.isNotEmpty(left)) {
                buffer.append("&").append(left);
            }
        }

        if (!toHash && StringUtils.isNotEmpty(segmentHash)){
            buffer.append("#");
            buffer.append(segmentHash);
        }

        return buffer.toString();
    }
}
